<template>
  <h1 style="font-size: 3vw;margin-bottom: 20px">{{ product.name }}</h1>
  <div v-if="obj.dataGet">
    <div style="font-size: 25px;font-weight: bold; margin-bottom: 20px">{{ product.descnn }}</div>
    <el-breadcrumb separator="/" class="bread">
      <el-breadcrumb-item>
        <el-link :underline="false" @click="router.push('/index')">首页</el-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <el-link :underline="false" @click="router.push('/categories')">categories</el-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item>
        <el-link :underline="false" @click="router.push(`/categories/${params.catid}`)">{{ params.catid }}
        </el-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item>{{ product.name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="pro-item">
      <div style="margin-right: 20px">
        <img :src="product.descn" alt="{{product.name}}"/>
      </div>
      <div style="display: flex;flex-direction: column;padding-top: 10px">
                <span style="font-size: 25px;font-weight: bold; margin-bottom: 20px;text-align: left">{{
                    product.name
                  }}</span>
        <span class="price">${{ obj.price }}</span>
        <el-radio-group style="margin-top: 20px;margin-bottom: 20px" v-model="radio" @change="itemChange">
          <el-radio-button v-for="item in itemList.data" :label="item.itemid">{{ item.itemid }}
          </el-radio-button>
        </el-radio-group>
        <span style="font-size: 15px;text-align: left;margin-bottom: 20px">{{ obj.descn }}</span>
        <span style="font-size: 15px;text-align: left;margin-bottom: 20px">库存：{{ obj.qty }}</span>
        <el-input-number v-model="obj.num" :min="1" :max="obj.maxnum" :disabled="obj.isInput"/>
        <div style="margin-top: 20px;text-align: left">
          <button class="buy" @click="buyAction">
            <span
                style="display: inline; font-size: 16px; font-weight: bold; color: rgb(255, 255, 255);">立即购买</span>
          </button>
          <button class="cart" @click="cartAction">
            <span
                style="display: inline; font-size: 16px; font-weight: bold; color: rgb(255, 255, 255);">加入购物车</span>
          </button>
        </div>
      </div>
    </div>
    <el-dialog
        v-model="buyDialog"
        :title="`购买${product.name}--${radio}`"
        width="30%"
    >
      <el-radio-group v-model="address"
                      size="small"
                      style="display: flex;flex-direction: column;text-align: center"
                      v-show="addressesData.data.length != 0">
        <el-radio v-for="item in addressesData.data"
                  class="address-choose"
                  :label="`${item.province}省${item.city}市${item.district}区${item.address}`" border>
          收件人:{{ item.name }}<br/>
          详细地址:{{ item.province }}省{{ item.city }}市{{ item.district }}区{{ item.address }}
        </el-radio>
      </el-radio-group>
      <span v-show="addressesData.data.length == 0">
        您还没有地址可以选哦，点击
        <el-link type="primary"
                 @click="router.push({path:`/account/${obj.loginName}`,query: {type:'first'}})">此处去添加地址
        </el-link>
      </span>
      <el-input-number v-model="obj.num" :min="1" :max="obj.maxnum" :disabled="obj.isInput"/>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="buyDialog = false">取消</el-button>
                    <el-button type="primary" @click="buy">
                        购买
                    </el-button>
                </span>
      </template>
    </el-dialog>
  </div>

</template>

<script setup lang="ts">
import {useRoute} from "vue-router";
import {get, post_json} from '@/assets/ts/ruquestMethod'
import router from "@/router";
import {reactive, ref} from "vue";
import type {Product, ItemData, AddressData} from "@/assets/ts/Interfaces";
import {ElMessage} from "element-plus";

let isLogin: boolean, loginName: string
const {params} = useRoute()
const radio = ref()
const address = ref('')
const buyDialog = ref(false)
let obj = reactive({
  itemList: '',
  dataGet: false,
  price: 0,
  descn: '',
  qty: 0,
  num: 1,
  maxnum: 1,
  isInput: true,
  loginName: sessionStorage.getItem('loginName')
})
const addressesData = reactive<AddressData>({
  data: [{
    id: 0,
    username: '',
    name: '',
    province: '',
    city: '',
    district: '',
    address: ''
  }]
})
let product = reactive<Product>({
  productid: '',
  category: '',
  name: '',
  descn: '',
  descnn: ''
})
let itemList = reactive<ItemData>({
  data: [{
    attr1: '',
    itemid: '',
    listprice: 0,
    product: null,
    productid: '',
    qty: 0,
    unitcost: 0
  }]
})
get('/items/' + params.productId,
    (data: any) => {
      product = data.data.productInfo
      itemList.data = data.data.items
      obj.dataGet = true
    }
)

get('/accounts/islogin',
    (data: any) => {
      if (data.status === 0) {
        isLogin = false
      }
      if (data.status === 1) {
        isLogin = true
        loginName = data.data.userid
      }
    }
)
const itemChange = () => {
  for (let i = 0, j = itemList.data.length; i < j; i++) {
    if (itemList.data[i].itemid == radio.value) {
      obj.price = itemList.data[i].listprice
      obj.descn = `${itemList.data[i].itemid}:${itemList.data[i].attr1}`
      obj.qty = itemList.data[i].qty
      obj.maxnum = itemList.data[i].qty
      obj.isInput = false
      break
    }
  }
}
const getAddress = () => {
  get('/addresses',
      (response: any) => {
        if (response.status == 1) {
          addressesData.data = response.data
        }
      }
  )
}
const buyAction = () => {
  if (!isLogin) {
    ElMessage.warning('您还未登录，请登录')
    return
  } else if (radio.value == null) {
    ElMessage.warning("您还未选择具体的商品！")
    return;
  }
  getAddress()
  buyDialog.value = true
}
const buy = () => {
  if (address.value == '') {
    ElMessage.warning('请选择地址')
    return
  }
  post_json('/orders',
      {
        descn: product.descn,
        productid: product.productid,
        itemid: radio.value,
        num: obj.num,
        totalcost: obj.price * obj.num,
        address: address.value,
        productname: product.name
      },
      (response: any) => {
        ElMessage.success('下单成功！')
        obj.qty -= obj.num;
        obj.num = 1;
        console.log(response)
      }
  )
  buyDialog.value = false
}
const cartAction = () => {
  if (!isLogin) {
    ElMessage.warning('您还未登录，请登录')
    return
  } else if (radio.value == null) {
    ElMessage.warning("您还未选择具体的商品！")
    return;
  }
  post_json('/carts',
      {
        username: loginName,
        descn: product.descn,
        itemId: radio.value,
        productName: product.name,
        num: 1,
        listprice: obj.price,
        totalcost: obj.price,
        productId: product.productid
      },
      (response: any) => {
        console.log(response)
        if (response.status == 1) {
          ElMessage({
            message: response.message,
            type: 'success'
          })
        }
      }
  )
}
</script>

<style scoped>
.bread {
  margin-left: 15%;
  margin-bottom: 20px;
}

.pro-item {
  display: flex;
  flex-direction: row;
  margin-left: 25%;
  margin-bottom: 20px;
  width: 900px;
}

.pro-item img {
  border-radius: 5%;
  width: 474px;
  height: 500px;
}

.price {
  font-size: 25px;
  font-weight: bold;
  color: rgb(255, 79, 0);
  text-align: left;
}

button.buy {
  background: linear-gradient(90deg, rgb(255, 119, 0), rgb(255, 73, 0));
  border-style: none;
  border-bottom-left-radius: 10px;
  border-top-left-radius: 10px;
  width: 136px;
  height: 48px;
  box-shadow: rgba(255, 119, 0, 0.2) 0 9px 13px 0;
  cursor: pointer;
}

button.cart {
  background: linear-gradient(90deg, rgb(255, 203, 0), rgb(255, 148, 2));
  border-style: none;
  border-bottom-right-radius: 10px;
  border-top-right-radius: 10px;
  width: 136px;
  height: 48px;
  box-shadow: rgba(255, 203, 0, 0.2) 0 9px 13px 0;
  cursor: pointer;

}

.address-choose {
  min-height: 40px;
  margin: 10px 0;
}
</style>